var audioRecorder;
var recorderTime;

initRecorder();
function initRecorder() {
	try {
		audioRecorder = require('recorder');
		audioRecorder.init();
		
		amrRecorder = require('recorder');
		amrRecorder.init();
	} catch (e) {
		agentGlobalVar.recorder = null;
	}
}


function recordAudio(){
	if(agentSelfInfo) {//THE AGENT
		if(!currentVisitorId) {
			showLayer(AGENT_TEXT.DO_SEND_ONLY_TALKING);
			return false;
		}
	}
	
	getAudioMedia(function(data) {
		if (data == true) {
			startRecordAudio();
		} else {
			layer.msg('您设备上的麦克风无法使用，如果确认存在麦克风设备请重启浏览器重试');
		}
	});	
}


function getAudioMedia(callback) {
	if (navigator.getUserMedia) {
		try {
			navigator.getUserMedia({audio: true, video: false},
				function(stream) {
					callback(true);
				},
				function(){
					callback(false);
				});
		} catch (err){
			callback(false);
		}
	} else if (navigator.webkitGetUserMedia) {
		try {
			navigator.webkitGetUserMedia('audio', function(stream) {
				callback(true);
			},
			function(){
				callback(false);
			});
		} catch (err) {
			callback(false);
		}
	}
}


/**
 * 开始语音录制
 * @returns
 */
function startRecordAudio() {
	if($("#audioRecording").is(':visible')) {
		showLayer(TEXT.RECORDING);
		return;
	}
	if (audioRecorder) {
		audioRecorder.reset();
		audioRecorder.startRecording();
		startAudioTime();
		$("#audioRecording").show();
	}
}

var recordDuration = 0;
function startAudioTime() {
	if (recorderTime) {
		clearInterval(recorderTime);
		recorderTime = null;
	}
	recordDuration = 0;
	$("#audioTime").html(recordDuration);
	recorderTime = setInterval(function(){
		recordDuration++;
		$("#audioTime").html(recordDuration);
		if (recordDuration == 60) {
			cancelRecordAudio(true);
		}
	}, 1000);
}

function cancelRecordAudio(keepShow) {
	if(audioRecorder) {
		audioRecorder.stopRecording();
		clearInterval(recorderTime);
		recorderTime = null;
		if(keepShow == true) {
		} else {
			audioRecorder.reset();
			$("#audioRecording").hide();
		}
	} else {
		showLayer(TEXT.DO_ERROR);
	}
}



function sendRecordAudio() {
	if(audioRecorder) {
		audioRecorder.encodeAMR(function(buffer) {
			//停止录制，并隐藏
			cancelRecordAudio();
			var blob = new Blob([buffer], {type: 'application/octet-stream'});
			sendAudio(blob, recordDuration);
	});
	} else {
		showLayer(TEXT.DO_ERROR);
	}
}

function sendAudio(blob, duration) {
	var formData = new FormData(); 
	formData.append("file", blob); 
	formData.append("bizType", "CHAT");
	formData.append("multiType", "AUDIO");
	try {
		if(crm) {//THE VISITOR
			formData.append("id", crm.id);
		}
	} catch(e) {
	}
	 
	$.ajax({
		url: UPLOAD_URL,
		data: formData,
		cache: false,
		contentType: false,
		processData: false,
		type: 'POST',
		dataType:"json",
		success: function(resp) {
			if (resp.code == 0) {
				resp.duration = duration;
				doSend(JSON.stringify(resp), "", MULIT_TYPE.AUDIO);
			} else {
				showLayer(TEXT.DO_ERROR);
			}
		}, error: function(resp) {
			showLayer(TEXT.DO_ERROR);
		}
	});		
}

var audioPlayInterval;
var audioPlayCounting = 0;
function playAmr(url, msgID, duration) {
    if (amrRecorder) {
        if (url && $("#audio-play-" + msgID).attr("class") == "autioBtnPlay") { //可播放
            $("#audio-play-" + msgID).removeClass("autioBtnPlay").addClass("autioBtnStop");
            $("#progress-" + msgID).css("width", "0%");
            try {
                amrRecorder.playAmrURL(url, function(res) {
                    if (res !== false) {
                        audioPlayInterval = setInterval("countDown('" + msgID + "', " + duration + ")", 1000);
                    } else {
                        clientMsg(TEXT.DO_ERROR);
                        $("#voice-down-" + msgID).show();
                    }
                });
            } catch (err) {
                $("#progress-" + msgID).css("width", "0%");
                clientMsg(TEXT.DO_ERROR);
            }
        } else { //停止
            stopPlay(msgID);
        }
    } else {
        clientMsg(TEXT.DO_ERROR);
        $("#progress-" + msgID).css("width", "0%");
    }
}

function countDown(msgID, duration) {
    audioPlayCounting += 1;
    if (audioPlayCounting > duration) {
        stopPlay(msgID);
    } else {
    	var percent = (audioPlayCounting / duration)  * 100;
        $("#progress-" + msgID).css("width", percent + "%");
    }
}

function stopPlay(msgID) {
	$("#audio-play-" + msgID).removeClass("autioBtnStop").addClass("autioBtnPlay");
	$("#progress-" + msgID).css("width", "100%");
	amrRecorder.stopPlaying();
	if (audioPlayInterval) {
	    clearInterval(audioPlayInterval);
	    audioPlayInterval = null;
	    audioPlayCounting = 0;
	}
}